<?php
/**
 * Created by PhpStorm.
 * User: jason
 * Date: 2017/12/10
 * Time: 22:49
 */

namespace Home\Controller;


use Home\Service\ImageService;
use Home\Service\SheetService;
use OSS\Core\OssException;
use OSS\OssClient;
Vendor('OSS.autoload');

class UploadController extends HomeController
{
    public function __construct()
    {
        parent::__construct();
        $this->_initialize();
        $this->assign('nav', 'upload');
    }

    /**
     * 初始化参数
     */
    public function _initialize()
    {
        $this->accessKeyId = C('OSS.accessKeyId');
        $this->accessKeySecret = C('OSS.accessKeySecret');
        $this->endpoint = C('OSS.endpoint');
        $this->bucket = C('OSS.bucket')['user-sheetimg'];
        $this->ossDomain = C('OSS.ossDomain')['user-sheetimg'];

        try {
            $this->oss = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    /**
     * 用户提交谱单页面
     */
    public function User()
    {
        $this->display('Upload/user');
    }

    /**
     * 保存谱单
     */
    public function save()
    {
        $params = I('post.');
        $service = new SheetService();
        $res = $service->addSheet($params);
        if (!$res) {
            $return['code'] = 600;
            $return['msg'] = 'failed';
            $this->ajaxReturn($return);
        }
        $return['code'] = 200;
        $return['msg'] = 'success';
        $this->ajaxReturn($return);
    }


    /**
     * 上传文件到本地
     * @param array $file
     * @param unknown $uploads_dir
     * @return string
     */
    public function uploadFiles()
    {
        $file = $_FILES['images'];
        $uploads_dir = RUNTIME_PATH."Uploads";
        $this->mkdirs($uploads_dir);
        $tmp_name = $file["tmp_name"];
        $name = $file["name"];
        move_uploaded_file($tmp_name, $uploads_dir . '/' . $name);
        $img_url = $uploads_dir . "/" . $name;
        $response = array("img_url"=>$img_url);
        $this->success($response);
    }

    /**
     * 上传曲谱图片到aliyun
     */
    public function uploadSheet($param)
    {
        $image_urls = $param['image_urls'];
        foreach ($image_urls as $image_url) {
            $file = explode('/', $image_url);
            $filename = $file[count($file)-1];
            try {

                //step-2: 上传图片到阿里云服务器
                $data = $this->oss->uploadFile($this->bucket, $param['name'] . "/" . $this->generateFileName($image_url), $image_url);
                unlink($image_url);

                //step-3: 上传成功后把图片信息保存到数据库
                $image = array(
                    "name"  =>  $filename,
                    "url"   =>  $data['oss-request-url'],
                    "img_type"  =>  10,
                );

                $imageService = new ImageService();
                $image_id[] = $imageService->saveImg($image);
            } catch (OssException $e) {
                return $e->getErrorMessage();
            }
        }
        return $image_id;
    }

    /**
     * 将文件内容md5加密，生成文件名
     * @param unknown $filePath
     */
    private function generateFileName($filePath){
        header('Content-type:text/html;charset=utf-8');
        //读取图片文件，转换成base64编码格式
        return md5(file_get_contents($filePath)).'.'.$this->get_extension($filePath);
    }

    /**
     * 获取文件后缀名
     * @param unknown $file
     * @return mixed
     */
    private function get_extension($file)
    {
        return pathinfo($file, PATHINFO_EXTENSION);
    }

    /**
     * 创建文件夹
     * @param $dir
     * @param int $mode
     * @return bool
     */
    private function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
        if (!$this->mkdirs(dirname($dir), $mode)) return FALSE;
        return @mkdir($dir, $mode);
    }

}